﻿using System;
using System.IO;

namespace MangosRestarter
{
    /// <summary>
    /// 配置文件辅助类
    /// </summary>
    internal static class ConfigHelper
    {
        private static readonly string ConfPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MangosRestarter.conf");

        internal static string MySqlPath = @"mysql5\bin\mysqld.exe";
        internal static string MySqlArgs = "--console --max_allowed_packet 128M";
        internal static bool StartMySql = true;
        internal static string WorldServerPath = "mangosd.exe";
        internal static string RealmServerPath = "realmd.exe";

        /// <summary>
        /// 确保默认配置文件存在
        /// </summary>
        internal static void EnsureDefaultConfig()
        {
            if (File.Exists(ConfPath)) return;

            try
            {
                var lines = new[]
                {
                    "# MangosRestarter 配置文件（可手动修改，重启程序即生效）",
                    "",
                    "# 世界服务器可执行文件路径（相对或绝对路径,默认：mangosd.exe）",
                    "WorldServerPath=mangosd.exe",
                    "",
                    "# 登陆服务器可执行文件路径（相对或绝对路径,默认：realmd.exe）",
                    "RealmServerPath=realmd.exe",
                    "",
                    "# 检测间隔（毫秒，1秒=1000毫秒）",
                    "CheckIntervalMs=3000",
                    "",
                    "# MySQL 服务器可执行文件路径（相对或绝对,默认：mysql5\\bin\\mysqld.exe）",
                    "MySqlPath=mysql5\\bin\\mysqld.exe",
                    "",
                    "# MySQL 启动参数",
                    "MySqlArgs=--console --max_allowed_packet 128M",
                    "",
                    "# 是否由 MangosRestarter 负责启动 MySQL（true/false）",
                    "StartMySql=true"
                };

                File.WriteAllLines(ConfPath, lines, System.Text.Encoding.UTF8);
                Logger.Write("已创建默认配置文件: MangosRestarter.conf");
            }
            catch (Exception ex)
            {
                Logger.Write($"创建默认配置文件失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 加载配置文件设置
        /// </summary>
        internal static void LoadSettings()
        {
            if (!File.Exists(ConfPath)) return;

            try
            {
                foreach (var line in File.ReadAllLines(ConfPath))
                {
                    if (string.IsNullOrWhiteSpace(line) || line.Trim().StartsWith("#"))
                        continue;

                    var kv = line.Split('=');
                    if (kv.Length < 2) continue;

                    var k = kv[0].Trim();
                    var v = kv[1].Trim();

                    switch (k)
                    {
                        case "WorldServerPath":
                            WorldServerPath = v;
                            break;
                        case "RealmServerPath":
                            RealmServerPath = v;
                            break;
                        case "MySqlPath":
                            MySqlPath = v;
                            break;
                        case "MySqlArgs":
                            MySqlArgs = v;
                            break;
                        case "StartMySql":
                            StartMySql = string.Equals(v, "true", StringComparison.OrdinalIgnoreCase);
                            break;
                        case "CheckIntervalMs":
                            if (int.TryParse(v, out var interval))
                                ServerWatcher.CheckIntervalMs = interval;
                            break;
                    }
                }

                Logger.Write($"配置文件加载完成 - 世界服务器: {WorldServerPath}, 登录服务器: {RealmServerPath}, 启动MySQL: {StartMySql}");
            }
            catch (Exception ex)
            {
                Logger.Write($"加载配置文件失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 验证配置文件有效性
        /// </summary>
        internal static bool ValidateConfig(out string error)
        {
            error = null;

            // 检查世界服务器路径
            var worldFullPath = GetFullPath(WorldServerPath);
            if (!File.Exists(worldFullPath))
            {
                error = $"世界服务器可执行文件不存在: {worldFullPath}";
                return false;
            }

            // 检查登录服务器路径
            var realmFullPath = GetFullPath(RealmServerPath);
            if (!File.Exists(realmFullPath))
            {
                error = $"登录服务器可执行文件不存在: {realmFullPath}";
                return false;
            }

            // 检查MySQL路径（如果配置了启动MySQL）
            if (StartMySql)
            {
                var mysqlFullPath = GetFullPath(MySqlPath);
                if (!File.Exists(mysqlFullPath))
                {
                    error = $"MySQL可执行文件不存在: {mysqlFullPath}";
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// 获取文件的完整路径（如果是相对路径，则转换为绝对路径）
        /// </summary>
        internal static string GetFullPath(string path)
        {
            if (Path.IsPathRooted(path))
                return path;

            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
        }
    }
}